package com.seckillpro.seckill_pro.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seckillpro.seckill_pro.pojo.TUser;
import com.seckillpro.seckill_pro.service.ITGoodsService;
import com.seckillpro.seckill_pro.utils.CookieUtil;
import com.seckillpro.seckill_pro.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.SecKillpro.SecKill_pro.controller
 * @ClassName: GoodsController
 * @Author: lyx
 * @CreateTime: 2021/3/4 9:32
 * @Description:
 */

@Slf4j
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private ITGoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    //themeleaf渲染引擎
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 跳转商品列表页
     * windows 150000 样本 qbs
     *
     * @param model
     * @param tUser
     * @return
     */

    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, TUser tUser,
                         HttpServletResponse response, HttpServletRequest request) {

        //Redis中获取页面，如果不为空，直接返回页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        if (!(null == html || "".equals(html))) {
            return html;
        }
        model.addAttribute("tUser", tUser);
        model.addAttribute("goodList", goodsService.findGoodsVoList());
//        return "goodsList";

//        如果为null手动渲染thymeleaf模板，存如Redis并返回，而不是SpringBoot来渲染
        WebContext context = new WebContext(request, response, request.getServletContext(),
                request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
        if (!(null == html || "".equals(html))) {
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }


    /**
     * 跳转商品详情页面
     *
     * @param goodId
     * @return
     */
    @RequestMapping(value = "/toDetail2/{goodId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail2(Model model, TUser tUser, @PathVariable Long goodId,
                            HttpServletResponse response, HttpServletRequest request) {

        //Redis中获取页面，如果不为空，直接返回页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail" + goodId);
        if (!(null == html || "".equals(html))) {
            return html;
        }

        model.addAttribute("tUser", tUser);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodId(goodId);
        model.addAttribute("good", goodsVo);

        //获取开始时间
        Date startDate = goodsVo.getStartDate();
        //获取结束时间
        Date endDate = goodsVo.getEndDate();
        //是否还再秒杀时间状态
        int SecKillStatus = 0;

        //秒杀倒计时
        int remainSeconds = 0;

        if (new Date().before(startDate)) {
            //秒杀还没开始
            remainSeconds = ((int) (startDate.getTime() - new Date().getTime()) / 1000);
        } else if (new Date().after(endDate)) {
            //秒杀已结束
            SecKillStatus = 2;
        } else {
            //秒杀进行中
            SecKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("SecKillStatus", SecKillStatus);

        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);

        if ((null == html | "".equals(html))) {
            valueOperations.set("goodsDetail" + goodId, html, 60, TimeUnit.SECONDS);
        }
        return html;
    }


    /**
     * 跳转商品详情页面
     *
     * @param goodId
     * @return
     */
    @RequestMapping("/detail/{goodId}")
    @ResponseBody
    public RespBean toDetail(Model model, TUser tUser, @PathVariable Long goodId) {
        model.addAttribute("tUser", tUser);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodId(goodId);
        model.addAttribute("good", goodsVo);

        //获取开始时间
        Date startDate = goodsVo.getStartDate();
        //获取结束时间
        Date endDate = goodsVo.getEndDate();
        //是否还再秒杀时间状态
        int secKillStatus = 0;

        //秒杀倒计时
        int remainSeconds = 0;

        if (new Date().before(startDate)) {
            //秒杀还没开始
            remainSeconds = ((int) (startDate.getTime() - new Date().getTime()) / 1000);
        } else if (new Date().after(endDate)) {
            //秒杀已结束
            secKillStatus = 2;
        } else {
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);

        GoodDetailVo goodDetailVo = new GoodDetailVo();
        goodDetailVo.setUser(tUser);
        goodDetailVo.setGoodsVo(goodsVo);
        goodDetailVo.setSecKillStatus(secKillStatus);
        goodDetailVo.setRemainSeconds(remainSeconds);


        return RespBean.success(goodDetailVo);
    }


    @RequestMapping("/toAdd")
    public String toAdd() {
        return "addGood";
    }


    @ResponseBody
    @PostMapping("/addGood")
    public RespBean addGood(AddGoodVo addGoodVo) {

        //文件上传
        MultipartFile imgName = addGoodVo.getImgLoad();
        if (imgName.getSize() > 10485760) {
            return RespBean.error(RespBeanEnum.FILE_SIZE_OVER);
        }
        try {
            //处理文件上传
            String localPath = "C:\\Users\\lyx\\Desktop\\secKillPro\\seckill_pro\\seckillpro\\src\\main\\resources\\static\\imgs";
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/imgs";
            System.out.println(realPath);
            File localDir = new File(localPath);
            File realDir = new File(realPath);
            if (!localDir.exists()) {
                log.info(localPath + ":不存在");
            }
            if (!realDir.exists()) {
                log.info(realDir + ":不存在");
            }

            String newFileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + UUID.randomUUID().toString();
            String extension = FilenameUtils.getExtension(imgName.getOriginalFilename());

            String newName = newFileNamePrefix + "." + extension;
            addGoodVo.setNewName(newName);
            File desFile = new File(realPath + "/" + newName);

            //上传到服务器
            FileUtils.copyInputStreamToFile(imgName.getInputStream(), desFile);
            //上传到本地
            imgName.transferTo(new File(localDir, newName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return goodsService.addGood(addGoodVo);
    }

    @RequestMapping("/delete/{goodId}")
    @ResponseBody
    public RespBean deleteGood(@PathVariable Long goodId, String userId) {

        System.out.println(userId);
        if (!userId.equals("17621806946")) {
            return RespBean.error(RespBeanEnum.IS_NOT_ADMIN);
        }
        RespBean respBean = goodsService.removeGood(goodId);
        Object o = redisTemplate.opsForValue().get("goodsList");
        if (!ObjectUtil.isEmpty(o)){

            redisTemplate.delete("goodsList");
        }
        return respBean;
    }

}